<template>
	<a-modal
		:visible="visible"
		width="1100px"
		title="退租"
		centered
		destroyOnClose
		:maskClosable="false"
		@cancel="cancel"
		:footer="null"
		:bodyStyle="{padding: 0}">
		<a-form
			ref="formRef"
			:model="modelRef"
			:rules="formRules"
			layout="horizontal"
			class="flex-container-nomal"
			:labelCol="{style: {width: '120px'}}"
			style="height: 80vh"
			@finish="submit">
			<div class="flex1 auto-y">
				<a-space :size="12" direction="vertical" style="width: 100%">
					<a-row :gutter="10">
						该房间还有{{ totalMoney.notPayNumber }}个账单未结，共计费用{{ totalMoney.total }}元，请及时与承租人结算业务
					</a-row>

					<a-row :gutter="10">
						<a-col>
							<a-form-item label="合同退租日期" name="" :rules="[{required: true, message: '请选择合同退租日期'}]">
								<a-date-picker
									v-model:value="endDate"
									:value-format="DATE_FORMAT.DATE"
									disabled
									:disabled-date="disabledDate" />
							</a-form-item>
						</a-col>

						<a-col>
							<a-form-item label="实际退租日期" name="quiteDate" :rules="[{required: true, message: '请选择实际退租日期'}]">
								<a-date-picker
									v-model:value="modelRef.quiteDate"
									:value-format="DATE_FORMAT.DATE"
									:disabled="
										(contractDetail.contractStatus == 23 || props.resubmitId !== '') &&
										![1, 2, 3].includes(modelRef.backType)
									"
									:disabled-date="disabledDate"
									@change="changeDate" />
							</a-form-item>
						</a-col>
					</a-row>

					<a-row :gutter="16" v-if="houseRoomDTOList.length">
						<a-col>
							<a-select v-model:value="houseId" placeholder="请选择房间" style="width: 500px" @change="changeHouse">
								<a-select-option v-for="item in houseRoomDTOList" :key="item.id" :value="item.id">
									{{ item.name }}
								</a-select-option>
							</a-select>
						</a-col>

						<a-col>
							<a-button type="primary" @click="houseSwitch('up')">上一套</a-button>
						</a-col>

						<a-col>
							<a-button type="primary" @click="houseSwitch('down')">下一套</a-button>
						</a-col>

						<!-- 重新提交不展示退房交割单 -->
						<a-col>
							<a-space :size="10" v-if="!props.resubmitId">
								<a-col>
									<a-button v-if="!isShow" type="primary" @click="addClick" style="width: 150px">
										<check-outlined v-if="JSON.stringify(houseDeliveryFroms[houseIndex]) != '{}'" />
										<plus-outlined v-else />
										确认退房交割单
									</a-button>
								</a-col>
								<a-col>
									<a-button
										v-if="!isShow"
										type="primary"
										@click="batchConfirm"
										style="width: 180px"
										:disabled="disabledBatchConfirm">
										<check-outlined v-if="JSON.stringify(houseDeliveryFroms[houseIndex]) != '{}'" />
										<plus-outlined v-else />
										批量确认退房交割单
									</a-button>
								</a-col>
							</a-space>
						</a-col>
					</a-row>

					<div>
						<template v-for="device in devices" :key="device.type">
							<template v-if="device.bind && device.online !== 1">
								<span style="color: #d9001b">
									{{ deviceText[device.type] ? deviceText[device.type] : '' }}
								</span>
								<br />
							</template>
						</template>

						<span v-if="offlineCount" style="color: #d9001b">*门禁已离线，待门禁在线后删除开门权限</span>
					</div>
				</a-space>
			</div>

			<div class="a-modal-dialog-footer">
				<a-space :size="12">
					<a-button @click="cancel">取消</a-button>
					<a-button :loading="loading" :disabled="loading" type="primary" html-type="submit">确定</a-button>
				</a-space>
			</div>
		</a-form>

		<lease-off-settlement
			v-model:visible="deliveryVisible"
			:id="contractId"
			:houseId="houseId"
			:data="houseDeliveryFroms[houseIndex]"
			@success="getDelivery" />
		<generate-bill v-model:visible="visibles.generateBill" :data="[]" :inpude-show="[]" />
		<!-- 账单预览 -->
		<batch-bill-preview
			v-model:visible="visibles.preview"
			:contract="modelRef"
			@success="sendRequest"
			:returnCostSide="returnCostSide" />
		<batch-confirm-dialog
			v-model:visible="visibles.batchConfirm"
			:enter-prise-contract-list="houseRoomDTOList"
			@close="batchConfirmFinish"
			:is-settlement="false" />
	</a-modal>
</template>

<script setup lang="ts">
	import {computed, reactive, ref, watch} from 'vue'
	import {
		cabcelBreakAbnormalList,
		tenantBreakNormalList,
		batchQuitEnterContract,
		break_agreement_list,
		getDeviceByIds,
		accessControlStatus
	} from '@/api/contract'
	import {paymentAccountList} from '@/utils'
	import {MinusSquareOutlined, PlusOutlined, PlusSquareOutlined, CheckOutlined} from '@ant-design/icons-vue'
	import dayjs, {Dayjs} from 'dayjs'
	import LeaseOffSettlement from '@/components/contract/tenant/lease-off-settlements.vue'
	import DATE_FORMAT, {nowDate} from 'yuxin-base/src/utils/date'
	import {getDispose, batchReturnResubmit, refundBill} from '@/api/charter-contract'
	import {RenterContract} from '@/interface/contract'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {DIC_LABEL_MAP} from 'yuxin-base/src/constant'
	import GenerateBill from '@/components/finance/generate-bill/index.vue'
	import {getEnterContractDetails, getRoomListPaging} from '@/api/charter-contract'
	import BatchBillPreview from '@/components/contract/contract-detail-dialog/charter-contract/batch-bill-preview.vue'
	import {VxeTablePropTypes} from 'vxe-table'
	import {message, Modal} from 'ant-design-vue'
	import XEUtils from 'xe-utils'
	import {deviceMap} from '@/constant/device'
	import BatchConfirmDialog from './batch-delivery-confirm.vue'

	const props = defineProps({
		visible: {
			type: Boolean,
			required: true
		},
		enterPriseContractId: {
			type: String,
			default: ''
		},
		applyId: {
			type: [String, Number],
			default: ''
		},
		quiteDate: {
			type: [String],
			default: ''
		},
		isShow: {
			type: Boolean,
			default: false
		},
		resubmitId: {
			type: String,
			default: ''
		}
	})

	const deliveryVisible = ref<boolean>(false)
	const modelRef = reactive<any>({
		quiteDate: '',
		remark: '',
		backType: 2,
		paymentAccountType: 1,
		paymentAccount: ''
	})
	const visibles = reactive({
		generateBill: false,
		preview: false,
		batchConfirm: false
	})
	const formRules = {}

	const feeSubject = ref<any>([])

	const disabledDate = (current: Dayjs) => {
		return false
		// 非合同即将搬入状态只能选择合同开始日期到当天日期
		// const validateBegineTime = dayjs(current).format('YYYY-MM-DD') < dayjs(contractDetail.value.beginTime).format('YYYY-MM-DD')
		// const validate = validateBegineTime || dayjs(current).format('YYYY-MM-DD') > dayjs().format('YYYY-MM-DD')
		// return modelRef.backType === 3 ? validateBegineTime : validate
		// return current && current.isAfter(dayjs().add(1, 'day'), 'day')
	}

	const contractId = ref<any>(null)

	const feeSubjectList = ref<any>([])

	const addClick = () => {
		deliveryVisible.value = true
	}
	//费用承担方相关
	const costSideList = reactive<any>([])
	const costSide = reactive<any>({
		1: '企业',
		2: '个人',
		3: '混合'
	})
	const getDisposeInfo = () => {
		getDispose(props.enterPriseContractId).then(res => {
			costSideList.value = res.data
		})
	}
	const returnCostSide = feeSubjectId => {
		return costSide[costSideList.value.filter(o => o.feeSubjectId === feeSubjectId)[0]?.type || 2]
	}

	const ids = ref([])
	/**
	 * 合同详情
	 */
	const contractDetail = ref<RenterContract>({})
	/**
	 * copy房源列表
	 */
	const houseRoomDTOList = ref<any>([])
	const houseId = ref<any>()
	const endDate = ref<any>('')
	const getData = async () => {
		// 获取合同详情
		await getEnterContractDetails(props.enterPriseContractId).then(({data}) => {
			ids.value = data.quiteContractIds
			contractDetail.value = data
			let date = new Date()
			let beginTime = new Date(data.beginTime)

			// 解约日期
			let quiteDate = ''
			if (props.quiteDate) {
				quiteDate = props.quiteDate
			} else {
				if (dayjs(date).valueOf() < dayjs(beginTime).valueOf()) {
					// quiteDate = dayjs(contractDetail.value.contractStatus == 23 ? new Date().getTime() : beginTime).format(DATE_FORMAT.DATE)
					quiteDate = nowDate()
				} else {
					quiteDate = nowDate()
				}
			}
			endDate.value = data.endTime
			modelRef.quiteDate = quiteDate
			if (data.contractStatus == 26) {
				modelRef.backType = 1
				// modelRef.quiteDate = data.endTime
			}
			changeDate()
		})

		// 获取房间列表
		getRoomListPaging({
			contractStatus: props.resubmitId ? 3 : 2,
			enterPriseContractId: props.enterPriseContractId,
			matchType: null,
			like: null,
			current: 1,
			size: 99999999,
			ids: ids.value,
			excludeTransition: 1
		}).then(({data}) => {
			houseRoomDTOList.value = data.records
			if (props.isShow && data.records.length === 1) {
				houseRoomDTOList.value.forEach((e: any) => {
					e.disabled = false
					e.name = e.fullAddress + '（已确认）'
					houseDeliveryFroms.value.push({})
					finances.value.push([])
				})
			} else {
				houseRoomDTOList.value.forEach((e: any) => {
					e.disabled = true
					e.name = e.fullAddress + '（未确认）'
					houseDeliveryFroms.value.push({})
					finances.value.push([])
				})
			}

			houseId.value = houseRoomDTOList.value[0]?.id
			contractId.value = houseRoomDTOList.value[0]?.contractId

			// 根据房间查询设备状态
			setEleAndWaterQuantity(houseRoomDTOList.value[0]?.id)

			// 查询门禁离线状态
			accessControlStatusF(houseRoomDTOList.value[0]?.communityId)

			// 判断是不是重新提交
			if (props.resubmitId) {
				resubmitIncomeList()
			} else {
				incomeList()
			}
		})

		// 获取费用科目列表
		settingApi.getDicListByLabel(DIC_LABEL_MAP.FEESUBJECT, {isUse: null}).then(({data}) => {
			data.forEach((item: any) => {
				item.selectable = false
				feeSubjectList.value.push(...item.metaList)
			})
			feeSubject.value = data
		})
	}

	const deviceText = {
		5: '*门锁已离线，待门锁在线后在智能门锁-授权信息中删除开门权限',
		4: '*电表已离线，请记录好电表读数后再进行退租',
		1: '*冷水表已离线，请记录好水表读数后再进行退租',
		2: '*中水表已离线，请记录好水表读数后再进行退租',
		3: '*热水表已离线，请记录好水表读数后再进行退租'
	}

	const deviceInfos = ref<any>({})
	const setEleAndWaterQuantity = id => {
		// 获取水电表详情
		getDeviceByIds([id]).then((res: any) => {
			deviceInfos.value = res.data[0] || {}
		})
	}

	const devices = computed(() => {
		const map = deviceMap()

		if (deviceInfos.value.deviceInfos) {
			for (let deviceInfo of deviceInfos.value.deviceInfos) {
				const device = map[deviceInfo.deviceType]

				if (device) {
					device.bind = true
					device.online = deviceInfo.online
				}
			}
		}
		return Object.values(map)
	})

	// 门禁离线数量
	const offlineCount = ref(0)
	// 获取门禁状态
	const accessControlStatusF = (communityId: string) => {
		accessControlStatus({
			communityId: communityId
		}).then((res: any) => {
			offlineCount.value = res?.data?.offlineCount || 0
		})
	}

	// table ---------------------------------------------------------------------------------------------------------
	// const mergeFooterItems = ref<VxeTablePropTypes.MergeFooterItems>([{row: 0, col: 0, rowspan: 1, colspan: 5}])
	const footerColspanMethod: VxeTablePropTypes.FooterSpanMethod = ({$rowIndex, _columnIndex}) => {
		if ($rowIndex === 0) {
			if (_columnIndex === 0) {
				return {
					rowspan: 1,
					colspan: 5
				}
			}
		}
	}
	const footerMethod: VxeTablePropTypes.FooterMethod = ({columns, data}) => {
		return [columns.map(() => null)]
	}

	const onNoramlChange = () => {
		if (modelRef.backType === 1) {
			// modelRef.quiteDate = contractDetail.value?.endTime || nowDate()
			modelRef.quiteDate = nowDate()
		} else {
			modelRef.quiteDate = nowDate()
		}

		// 切换付费类型清空物业交割单 账单和确认状态
		houseDeliveryFroms.value = []
		finances.value = []
		resetData()

		houseRoomDTOList.value.forEach((e: any) => {
			e.disabled = true
			e.name = e.fullAddress + '（未确认）'
			houseDeliveryFroms.value.push({})
		})
		if (props.resubmitId) {
			// 重新提交获取账单接口
			resubmitIncomeList()
		} else {
			incomeList()
		}
	}
	const changeDate = () => {
		// 解约日期
		if (modelRef.backType != 3) {
			if (dayjs(modelRef.quiteDate).valueOf() < dayjs(endDate.value).valueOf()) {
				modelRef.backType = 2
			} else {
				modelRef.backType = 1
			}
		}
		if (props.resubmitId) {
			resubmitIncomeList()
		} else {
			incomeList()
		}
	}
	/**
	 * 获取账单
	 */
	const incomeList = async (data: any = [],currentIndex?:number) => {
		const houseIndex1 = currentIndex > -1 ? currentIndex : houseIndex.value
		if (!houseRoomDTOList.value[houseIndex1]?.contractId) {
			return
		}
		const params = {
			contractId: houseRoomDTOList.value[houseIndex1]?.contractId,
			quiteDate: modelRef.quiteDate,
			meterReadRecordDtos: data
		}
		const apiMap = {
			1: tenantBreakNormalList,
			2: cabcelBreakAbnormalList,
			3: break_agreement_list
		}
		const res: any = await apiMap[modelRef.backType](params)
		if (res.code == 200) {
			res.data.forEach((item: any) => {
				item.disabled = true
				item.timeInfo = [item.beginDate, item.endDate]
				// 表单校验
				item.checkFeeSubjectId = true
				item.checkAmount = true
				item.checkTimeInfo = true
				item.contractId = houseRoomDTOList.value[houseIndex1].contractId
				item.houseId = houseRoomDTOList.value[houseIndex1].id
			})
			finances.value[houseIndex1] = res.data
		}
	}

	/*  重新提交获取账单*/
	const resubmitIncomeList = async (currentIndex?:number) => {
		const houseIndex1 = currentIndex> -1? currentIndex : houseIndex.value
		if (!houseRoomDTOList.value[houseIndex1]?.contractId) {
			return
		}
		await refundBill(houseRoomDTOList.value[houseIndex1]?.contractId).then((res: any) => {
			res.data?.billDetailDTOList.forEach((item: any) => {
				item.disabled = true
				item.timeInfo = [dayjs(item.beginTime).format(DATE_FORMAT.DATE), dayjs(item.endTime).format(DATE_FORMAT.DATE)]
				// 表单校验
				item.notOccurredMoney = item.notOccurredMoney ?? item.amount
				item.checkFeeSubjectId = true
				item.checkAmount = true
				item.checkTimeInfo = true
				item.contractId = houseRoomDTOList.value[houseIndex1]?.contractId
				item.houseId = houseRoomDTOList.value[houseIndex1].id
				item.payDate = dayjs(item?.predictTime).format(DATE_FORMAT.DATE)
				item.feeSubjectName = item?.feeSubjectValue
				item.beginDate = dayjs(item.beginTime).format(DATE_FORMAT.DATE)
				item.endDate = dayjs(item.endTime).format(DATE_FORMAT.DATE)
			})
			finances.value[houseIndex1] = res.data?.billDetailDTOList
		})
	}

	const billList = async (data: any = []) => {
		// console.log(data, '99')
		data.forEach((item: any) => {
			item.disabled = true
			item.timeInfo = [item.beginDate, item.endDate]
			// 表单校验
			item.checkFeeSubjectId = true
			item.checkAmount = true
			item.checkTimeInfo = true
			item.bizId = houseRoomDTOList.value[houseIndex.value].contractId
			item.contractId = houseRoomDTOList.value[houseIndex.value].contractId
			item.houseId = houseId.value

			item.isReleaseEnergy = true

			let index = finances.value[houseIndex.value].findIndex(o => o.id === item.id)
			// console.log(index, '00', houseIndex.value)
			if (index === -1) {
				// console.log(item)
				finances.value[houseIndex.value].push(item)
				// console.log(finances.value[houseIndex.value], 888)
			} else {
				finances.value[houseIndex.value][index] = {...item}
			}
		})
		// console.log(finances.value[houseIndex.value], 99)
	}

	const totalMoney = computed(() => {
		filterTableData()

		let total = 0
		/** 未支付账单数目 */
		let notPayNumber = 0
		if (finances.value[houseIndex.value]?.length) {
			for (let item of finances.value[houseIndex.value]) {
				if (item.feeDirection === 1) {
					notPayNumber++
					total += item.notOccurredMoney * 1
				} else {
					total -= item.notOccurredMoney * 1
				}
			}
		}

		return {
			total: total.toFixed(2),
			notPayNumber
		}
	})

	const columns = [
		{
			title: '收支类型',
			dataIndex: 'feeDirection',
			width: 100,
			align: 'center'
		},
		{
			title: '费用科目',
			dataIndex: 'feeSubjectId',
			width: 200,
			align: 'center'
		},
		{
			title: '金额(元)',
			dataIndex: 'notOccurredMoney',
			width: 150,
			align: 'center'
		},
		{
			title: '账单周期',
			key: 'cycle',
			align: 'center'
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			width: 100
		}
	]

	const finances = ref<any>([])
	const addTogether = (type: number | string) => {
		let obj = {
			// 收支金额
			notOccurredMoney: null,
			timeInfo: [],
			beginDate: '',
			// 费用类型
			costType: 0,
			endDate: '',
			// 费用方向【1收入2支出】
			feeDirection: type,
			// 费用科目id【字典】
			feeSubjectId: null,
			// 费用科目名称
			feeSubjectName: '',
			// 表单校验
			checkFeeSubjectId: true,
			checkAmount: true,
			checkTimeInfo: true,
			// 批量退租新增参数
			bizId: houseRoomDTOList.value[houseIndex.value]?.contractId,
			contractId: houseRoomDTOList.value[houseIndex.value]?.contractId,
			houseId: houseId.value
		}
		// if (props.resubmitId) {
		obj.resubmitIdStatus = true
		// }
		finances.value[houseIndex.value].push(obj)
	}
	const resetData = () => {
		disabledBatchConfirm.value = false
		failList.value = []
	}
	watch(
		() => props.visible,
		(newVal: boolean) => {
			if (newVal) {
				resetData()
				getData()
				getDisposeInfo()
			}
		}
	)

	const emit = defineEmits(['update:visible', 'success'])
	const cancel = () => {
		resetForm()
		emit('update:visible', false)
	}

	// 批量退租 变成数组结构
	const houseDeliveryFroms = ref<any[]>([])
	const getDelivery = (data: any) => {
		console.log(data)

		// 处理数据
		data.meterReadRecordDtos = data.meterReadRecordDtos.map(item => {
			return {
				...item,
				occurredMoney: 0,
				feeStatus: 1
			}
		})
		data.energyDictArr = data.energyDictArr.map(item => {
			return {
				...item,
				occurredMoney: 0,
				feeStatus: 1
			}
		})
		console.log('after==data===', data)

		// 数据结构改变后 处理方式变化
		data.compactType = 2
		data.deliveryType = 2
		data.compactId = houseRoomDTOList.value[houseIndex.value].contractId
		data.houseId = houseId.value

		// 新增或者替换
		houseDeliveryFroms.value.splice(houseIndex.value, 1, JSON.parse(JSON.stringify(data)))
		// 已确认
		let house = houseRoomDTOList.value[houseIndex.value]
		house.disabled = false
		house.name = house.fullAddress + '（已确认）'

		// 如果批量确认失败的列表中存在这条 就把列表中的这条数据去掉
		if (failList.value.length && failList.value.map(i => i.contractId).includes(data.compactId)) {
			failList.value = failList.value.filter(i => i.contractId !== data.compactId)
		}
		// 如果全部确认成功 禁用批量确认
		if (0 === houseRoomDTOList.value.filter(i => i.disabled).length) {
			disabledBatchConfirm.value = true
		}
		// console.log('getDelivery========', data, houseIndex.value, houseDeliveryFroms.value, houseRoomDTOList.value)

		// 设备费用存在 刷新账单
		if (data.meterReadRecordDtos && data.meterReadRecordDtos.length) {
			Modal.warning({
				title: '提示',
				content: '账单已更新，还请重新核对账单明细!'
			})
			if (props.resubmitId) {
				resubmitIncomeList()
			} else {
				incomeList(data.meterReadRecordDtos).finally(() => {
					billListInfo(data)
				})
			}
		} else {
			billListInfo(data)
		}
	}

	const billListInfo = (data: any) => {
		if (data?.earlyData && data.earlyData.length) {
			billList(data.earlyData)
		}
		// 能源预警
		if (data?.energyDictArr && data.energyDictArr.length) {
			billList(data.energyDictArr)
		}

		filterTableData()
	}

	/* 过滤金额为0  */
	const filterTableData = () => {
		finances.value[houseIndex.value] = finances.value[houseIndex.value]?.filter((item: any) => {
			return item.notOccurredMoney !== 0
		})
	}

	/**
	 * 当前房源下标
	 */
	const houseIndex = ref<any>(0)
	const houseSwitch = (type: string) => {
		// 包租合同 包租合同子合同 不展示退房交割单
		if (!props.isShow) {
			// 如果是重新提交的数据就跳过退房交割单的校验
			if (houseRoomDTOList.value[houseIndex.value].disabled && !props.resubmitId) {
				message.warn('请确认退房交割单')
				return
			}
		} else {
			let house = houseRoomDTOList.value[houseIndex.value]
			house.disabled = false
			house.name = house.fullAddress + '（已确认）'
		}

		if (type === 'up' && houseIndex.value === 0) {
			message.warn('已经是第一套了')
			return
		}
		if (type === 'down' && houseIndex.value === houseRoomDTOList.value.length - 1) {
			message.warn('已经是最后一套了')
			return
		}
		if (!props.resubmitId) {
			if (!checkTable()) {
				message.warn('请检查账单，不支持0元账单')
				return
			}
		}

		// 如果有失败的 下次切换直接跳转失败的 而不是下一个
		if (failList.value.length) {
			houseIndex.value = houseRoomDTOList.value.findIndex(i => i.contractId === failList.value[0].contractId)
		} else {
			let number = type === 'up' ? -1 : 1
			houseIndex.value += number
		}
		houseId.value = houseRoomDTOList.value[houseIndex.value].id
		contractId.value = houseRoomDTOList.value[houseIndex.value].contractId
		if (!finances.value[houseIndex.value]?.length) {
			// 根据房间查询设备状态
			setEleAndWaterQuantity(houseId.value)

			// 查询门禁离线状态
			accessControlStatusF(houseRoomDTOList.value[houseIndex.value]?.communityId)

			// 生成账单
			if (props.resubmitId) {
				resubmitIncomeList()
			} else {
				incomeList()
			}
		}
	}
	const changeHouse = (id: any) => {
		let currentHouse: any = {disabled: false}
		houseRoomDTOList.value.forEach((item, index) => {
			if (item.id === id) {
				currentHouse = item
				houseIndex.value = index
				contractId.value = item.contractId
				houseId.value = item.id
			}
		})
		if (!finances.value[houseIndex.value]?.length) {
			if (props.resubmitId) {
				resubmitIncomeList()
			} else {
				// 生成账单
				incomeList()
			}
		}

		// 如果当前房间未确认而且在批量确认失败的列表中 直接打开退租交割单
		if (currentHouse.disabled && failList.value.map(i => i.contractId).includes(contractId.value)) {
			addClick()
		}
	}

	/**
	 * 当前账单校验
	 */
	const checkTable = () => {
		let checkFee = false
		let j = finances.value[houseIndex.value]
		if (j.length) {
			for (let item of j) {
				item.checkFeeSubjectId = !item.feeSubjectId ? false : true
				if (!item.feeSubjectId) {
					checkFee = true
				}
				item.checkAmount = item.notOccurredMoney <= 0 || item.notOccurredMoney === null ? false : true
				if (item.notOccurredMoney <= 0 || item.notOccurredMoney === null) {
					checkFee = true
				}
				if (item.timeInfo.length == 0) {
					item.checkTimeInfo = false
					checkFee = true
				} else {
					item.beginDate = item.timeInfo[0]
					item.endDate = item.timeInfo[1]
					item.checkTimeInfo = true
				}
			}
		}
		if (checkFee) {
			return false
		}
		return true
	}

	const submit = async () => {
		if (modelRef.backType === 1 && dayjs().isBefore(modelRef.quiteDate, 'day')) {
			return message.error('合同未到期，无法办理到期退')
		}
		// 包租合同 包租合同子合同 不展示退房交割单
		if (!props.isShow) {
			if (houseRoomDTOList.value[houseIndex.value].disabled && !props.resubmitId) {
				return message.error('请确认物业交割单')
			}
		}
		if (!props.resubmitId) {
			if (!checkTable()) return
		}

		// 所有房间是否ok(如果是重新提交就不做校验)
		if (!props.resubmitId) {
			for (let i of houseRoomDTOList.value) {
				if (i.disabled) {
					return message.error('请确认所有退租房间')
				}
			}
		}
		// if (props.resubmitId) {
		// 82308字典修改
		let financesList: any = []
		finances.value.forEach((e: any) => {
			// 总金额=未发生金额+已发生金额

			e?.forEach((o: any) => {
				o.beginDate = o.timeInfo[0]
				o.endDate = o.timeInfo[1]
				o.beginTime = o.timeInfo[0]
				o.endTime = o.timeInfo[1]
				if (o.resubmitIdStatus) {
					o.payDate = dayjs(finances.value[0][0].predictTime).format(DATE_FORMAT.DATE)
					o.endTime = o.timeInfo[1]
					o.beginTime = o.timeInfo[0]
					o.beginDate = o.timeInfo[0]
					o.endDate = o.timeInfo[1]
				}
				o.amount = o.notOccurredMoney + (o.occurredMoney || 0)
				o.feeSubjectValue = feeSubjectList.value.find((d: any) => d.id === o.feeSubjectId)?.name
				o.feeSubjectName = o.feeSubjectValue
			})
			// 82308字典修改
			financesList.push(...XEUtils.clone(e, true))
		})
		// }
		// 82308字典修改
		// 保存 查询使用中字典 判断当前选择字典是否在使用中
		let typesList: any = []
		let list: any = []
		typesList = await settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT'], {isUse: 1})
		typesList.data.forEach((e: any) => {
			list.push(...e.metaList)
		})
		list.forEach((e: any) => {
			financesList.forEach((o: any) => {
				if (e.id === o.feeSubjectId) {
					o.active = true
				}
			})
		})
		if (!financesList?.every((e: any) => e?.active == true)) return message.error('选项已禁用，请选择其他选项！')

		// 账单预览
		modelRef.finances = finances.value
		modelRef.houseRoomDTOList = houseRoomDTOList.value
		visibles.preview = true
	}

	const loading = ref<any>(false)
	/**
	 * 最终退租接口
	 */
	const sendRequest = (data: any) => {
		if (props.isShow) {
			houseDeliveryFroms.value = []
		}
		loading.value = true
		let newFinances = JSON.parse(JSON.stringify(finances.value)).flat(Infinity) //过滤退租账单字段
		let financeList: any = []
		newFinances.map(o =>
			financeList.push({
				amount: o.amount,
				beginTime: o.beginTime,
				billType: o.billType,
				bizId: o.bizId,
				comment: o.comment,
				contractId: o.contractId,
				endTime: o.endTime,
				disabled: o.disabled,
				feeDirection: o.feeDirection,
				feeSubjectId: o.feeSubjectId,
				feeSubiectName: o.feeSubiectName,
				firstRead: o.firstRead,
				houseId: o.houseId,
				houseType: o.houseType,
				id: o.id,
				lastRead: o.lastRead,
				notOccurredMoney: o.notOccurredMoney,
				occurredMoney: o.occurredMoney,
				price: o.price,
				refundId: o.refundId,
				status: o.status
			})
		)
		const params: any = {
			backType: 4,
			enterPriseContractId: props.enterPriseContractId,
			finances: financeList,
			houseDeliveryFroms: houseDeliveryFroms.value,
			paymentAccountType: modelRef.paymentAccountType,
			paymentAccount: modelRef.paymentAccount,
			quiteDate: modelRef.quiteDate,
			remark: modelRef.remark,
			quiteBill: JSON.stringify(data), //解约账单
			isBillSettlement: 0
		}
		if (props.resubmitId) {
			// 重新提交的接口
			batchReturnResubmit(params)
				.then()
				.finally(() => {
					loading.value = false
					emit('success')
					cancel()
				})
		} else {
			batchQuitEnterContract(params)
				.then(() => {
					loading.value = false
					emit('success')
					cancel()
				})
				.finally(() => {
					loading.value = false
				})
		}
	}

	// 重置表单
	const formRef = ref<any>()
	const resetForm = () => {
		modelRef.paymentAccountType = 1
		finances.value = []
		houseIndex.value = 0
		houseDeliveryFroms.value = []
		houseId.value = null
		formRef.value.resetFields()
	}

	// 打开批量确认
	const disabledBatchConfirm = ref(false)
	const failList = ref<Array<any>>([])
	const batchConfirm = () => {
		failList.value = []
		visibles.batchConfirm = true
	}

	// 批量设置账单
	const batchSetFinance = (data: any = [], idx: number) => {
		data.forEach((item: any) => {
			item.disabled = true
			item.timeInfo = [item.beginDate, item.endDate]
			// 表单校验
			item.checkFeeSubjectId = true
			item.checkAmount = true
			item.checkTimeInfo = true
			item.bizId = houseRoomDTOList.value[idx].contractId
			item.contractId = houseRoomDTOList.value[idx].contractId
			item.houseId = houseRoomDTOList.value[idx].id

			let index = finances.value[idx].findIndex(o => o.id === item.id)
			if (index === -1) {
				finances.value[idx].push(item)
			} else {
				finances.value[idx][index] = {...item}
			}
		})
	}

	// 过滤账单
	const batchUpdateFinance = (data: any, _hIndex: number) => {
		if (data?.earlyData && data.earlyData.length) {
			batchSetFinance(data.earlyData, _hIndex)
		}
		// 能源预警
		if (data?.energyDictArr && data.energyDictArr.length) {
			batchSetFinance(data.energyDictArr, _hIndex)
		}

		finances.value[_hIndex] = finances.value[_hIndex].filter((item: any) => {
			return item.notOccurredMoney !== 0
		})
	}

	// 对批量确认完的交割单做处理
	const handleDeliveryRow = async (data, houseRoomDTOItem,updateList) => {
		const {contractId,id} = houseRoomDTOItem
		const _hIndex = houseRoomDTOList.value.findIndex(i => i.contractId === contractId)
		// 处理数据
		data.meterReadRecordDtos = data.meterReadRecordDtos.map(item => {
			return {
				...item,
				occurredMoney: 0,
				feeStatus: 1
			}
		})
		data.energyDictArr = data.energyDictArr.map(item => {
			return {
				...item,
				occurredMoney: 0,
				feeStatus: 1
			}
		})
		// 数据结构改变后 处理方式变化
		data.compactType = 2
		data.deliveryType = 2
		data.compactId = houseRoomDTOList.value[_hIndex].contractId
		data.houseId = id

		// 新增或者替换
		houseDeliveryFroms.value.splice(_hIndex, 1, JSON.parse(JSON.stringify(data)))
		// 已确认
		let house = houseRoomDTOList.value[_hIndex]
		house.disabled = false
		house.name = house.fullAddress + '（已确认）'

		// 设备费用存在 刷新账单
		// if (data.meterReadRecordDtos && data.meterReadRecordDtos.length) {
			updateList.push(_hIndex)
			if (props.resubmitId) {
				await resubmitIncomeList(_hIndex)
			} else {
				await incomeList(data.meterReadRecordDtos,_hIndex).finally(() => {
					batchUpdateFinance(data, _hIndex)
				})
			}
		// } else {
		// 	batchUpdateFinance(data, _hIndex)
		// }
	}

	// 批量确认结束回调
	const batchConfirmFinish = (unconfirmedList: Array<any>) => {
		// 确认失败的列表
		failList.value = unconfirmedList.filter(i => 2 === i.confirmStatus)
		// 是否有确认失败的数据
		const hasFail = !!failList.value.length
		// 对确认成功的数据进行处理
		const updateList = []
		houseRoomDTOList.value.forEach(i => {
			unconfirmedList
				.filter(i => 1 === i.confirmStatus)
				.forEach(async j => {
					if (i.contractId === j.contractId) {
						await handleDeliveryRow(XEUtils.clone(j.modelRef, true), i,updateList)
					}
				})
		})
		if(updateList.length) {
			Modal.warning({
					title: '提示',
					content: '账单已更新，还请重新核对账单明细!'
			})
		}
		// 如果有确认失败的 跳到失败的那个下标
		if (hasFail) {
			houseIndex.value = houseRoomDTOList.value.findIndex(i => i.contractId === failList.value[0].contractId)
		} else {
			// 已经全部确认后 切换到最后一套
			houseIndex.value = houseRoomDTOList.value.length - 1
		}

		houseId.value = houseRoomDTOList.value[houseIndex.value].id
		contractId.value = houseRoomDTOList.value[houseIndex.value].contractId

		if (!finances.value[houseIndex.value]?.length) {
			// 根据房间查询设备状态
			setEleAndWaterQuantity(houseId.value)

			// 查询门禁离线状态
			accessControlStatusF(houseRoomDTOList.value[houseIndex.value]?.communityId)

			// 生成账单
			if (props.resubmitId) {
				resubmitIncomeList()
			} else {
				incomeList()
			}
		}

		disabledBatchConfirm.value = true
	}
</script>

<style lang="less" scoped>
	:deep(.vxe-table--footer-wrapper.body--wrapper) {
		overflow: hidden;
	}
</style>
